import React, { useState, useEffect } from 'react';

import { InboxOutlined } from '@ant-design/icons';

import { commonUploadIotApi } from '@/api/commonApi';
import type { DeviceItemDetail, SysUploadDataOldType } from '@/api/deviceManagerApi';

/**
 * 文件记录组件属性
 */
interface FileRecordsProps {
  /** 设备详情 */
  deviceDetail: DeviceItemDetail;
  /** 上报数据 */
  reportData: SysUploadDataOldType | null;
  /** 上报数据加载状态 */
  reportLoading: boolean;
}

/**
 * 文件记录组件
 */
const FileRecords: React.FC<FileRecordsProps> = ({
  deviceDetail,
  reportData: _reportData,
  reportLoading: _reportLoading,
}) => {
  const [uploadingFiles, setUploadingFiles] = useState<any[]>([]);
  const [storageInfo, setStorageInfo] = useState({
    used: '0KB',
    total: '1024MB',
    fileCount: 0,
    maxFiles: 1000,
  });

  // 获取存储空间信息
  const fetchStorageInfo = async () => {
    try {
      // 这里应该调用实际的API获取存储空间信息
      // 暂时使用模拟数据
      const mockStorageInfo = {
        used: '102MB',
        total: '1024MB',
        fileCount: 0,
        maxFiles: 1000,
      };
      setStorageInfo(mockStorageInfo);
    } catch (error) {
      console.error('获取存储空间信息失败:', error);
    }
  };

  // 处理单个文件上传
  const handleSingleFileUpload = async (file: any) => {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('deviceId', deviceDetail.id?.toString() || '');

    try {
      const response = await commonUploadIotApi(formData);
      if (response.success) {
        window.$message.success(`文件 ${file.name} 上传成功`);
        // 刷新存储信息
        fetchStorageInfo();
        return true;
      } else {
        throw new Error(response.message || '上传失败');
      }
    } catch (error) {
      window.$message.error(
        `文件 ${file.name} 上传失败: ${error instanceof Error ? error.message : '未知错误'}`
      );
      return false;
    }
  };

  // 处理文件变化（自动上传）
  const handleFileChange = async (info: any) => {
    const { fileList } = info;

    // 找到新添加的文件（状态为undefined的文件）
    const newFiles = fileList.filter((file: any) => !file.status);

    // 对新文件进行自动上传
    for (const file of newFiles) {
      if (file.originFileObj) {
        // 设置文件状态为上传中
        file.status = 'uploading';
        setUploadingFiles([...fileList]);

        // 执行上传
        const success = await handleSingleFileUpload(file.originFileObj);

        // 更新文件状态
        file.status = success ? 'done' : 'error';
        setUploadingFiles([...fileList]);
      }
    }
  };

  // 初始化数据
  useEffect(() => {
    fetchStorageInfo();
  }, []);

  return (
    <div className="p-4">
      {/* 存储空间信息 */}
      <AAlert
        message={
          <div className="flex justify-between items-center">
            <span>
              当前账号存储空间已占用{' '}
              <span className="text-blue-500 font-medium">
                {storageInfo.used}/{storageInfo.total}
              </span>
            </span>
            <span>
              该设备文件数量{' '}
              <span className="text-blue-500 font-medium">
                {storageInfo.fileCount}/{storageInfo.maxFiles}
              </span>
            </span>
          </div>
        }
        type="info"
        showIcon={false}
        className="mb-4"
        style={{
          border: '1px solid #d9d9d9',
          borderRadius: '6px',
          backgroundColor: '#f6f6f6',
        }}
      />

      {/* 文件上传区域 */}
      <div
        style={{
          border: '2px dashed #d9d9d9',
          borderRadius: '6px',
          padding: '60px 20px',
          textAlign: 'center',
          backgroundColor: '#fafafa',
          minHeight: '300px',
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'center',
          alignItems: 'center',
        }}
      >
        <AUpload.Dragger
          multiple
          beforeUpload={() => false} // 阻止自动上传
          onChange={handleFileChange}
          fileList={uploadingFiles}
          onRemove={file => {
            setUploadingFiles(prev => prev.filter(f => f.uid !== file.uid));
          }}
          style={{
            border: 'none',
            backgroundColor: 'transparent',
            padding: 0,
          }}
          className="custom-upload-dragger"
        >
          <div style={{ marginBottom: '20px' }}>
            <InboxOutlined style={{ fontSize: 48, color: '#1890ff' }} />
          </div>
          <AButton type="primary" size="large" style={{ marginBottom: '20px' }}>
            选择文件
          </AButton>
          <p style={{ color: '#999', fontSize: 14, margin: 0, lineHeight: '20px' }}>
            单个账号最多储存1G文件；单个设备最多储存1000个文件；单个文件在平台最多保存3个月；目前支持图片文件和文本文件
          </p>
        </AUpload.Dragger>
      </div>
    </div>
  );
};

export default FileRecords;
